package com.android.baselibrary.util;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.SPUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018/6/12.
 */

public class Util {

    /**
     * 获取对象反射类型
     */
    public static Type getReflectType(Object object) {
        Type type;
        Type[] types = object.getClass().getGenericInterfaces();
        if (types.length > 0) {
            // 如果这个监听对象是直接实现了接口
            type = ((ParameterizedType) types[0]).getActualTypeArguments()[0];
        } else {
            // 如果这个监听对象是通过类继承
            type = ((ParameterizedType) object.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }
        return type;
    }

    static String[] goodImgs = {
            "https://www.ikea.cn/category-images/Category_sofas-and-armchairs.jpg?imwidth=300",
            "https://www.ikea.cn/ext/ingkadam/m/61ffc30f8edb181c/original/PH172132-crop003.jpg?f=xs",
            "https://www.ikea.cn/cn/zh/images/products/strandmon-si-jia-meng-kao-bei-yi-si-ke-te-bo-huang-se__0837297_PE601176_S5.JPG?f=xxs",
            "https://www.ikea.cn/revamp/childrens-desks_24714.jpg?imwidth=300",
            "https://www.ikea.cn/revamp/childrens-chests-of-drawers_18708.jpg?imwidth=300",
            "https://www.ikea.cn/revamp/decorative-accessories_24924.jpg?imwidth=300",
            "https://www.ikea.cn/category-images/Category_vases-and-bowls.jpg?imwidth=300",
            "https://www.ikea.cn/ext/ingkadam/m/164a00bb513632d7/original/PH171286-crop001.jpg?f=xs",
            "https://www.ikea.cn/cn/zh/images/products/pjaetteryd-pi-ya-te-tu-pian-cai-se-xun-lu__0689874_PE723123_S5.JPG?f=xxs",
            "https://www.ikea.cn/category-images/Category_childrens-boxes-and-baskets.jpg?imwidth=500",
            "https://www.ikea.cn/ext/ingkadam/m/3e3dc77eda5453c/original/PH173338-crop001.jpg?f=xs",
            "https://www.ikea.cn/images/jia1-ju1-yong4-pin3-b7571f84430217bc546ce5ebd5657127.jpg?f=xs",
            "https://www.ikea.cn/ext/ingkadam/m/58e107bc54ff5cf2/original/PH171927-crop001.jpg?f=xs",
            "https://www.ikea.cn/ext/ingkadam/m/1dc1af1325642950/original/PH175423-crop001.jpg?f=xs",
            "https://www.ikea.cn/ext/ingkadam/m/5c703b8229836cc7/original/PH174039-crop001.jpg?f=xl"
    };

    static String[] headImgs = {
        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201712%2F16%2F20171216164236_HMGVu.gif&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1612974260&t=7fc9ded801bd4303548b3fcc01e808ed",
            "",
            "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1812993978,4158651947&fm=26&gp=0.jpg",
            "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2752148155,155093617&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1549131754,2955370505&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3335200364,664435613&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3461339905,3407964579&fm=11&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=249424419,860932438&fm=11&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2184463790,438646211&fm=11&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3156043369,3023538154&fm=11&gp=0.jpg",
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3815481620,1710167837&fm=11&gp=0.jpg"
    };

    public static String getGoodsImg()
    {
        int random = new Random().nextInt(goodImgs.length);
        return goodImgs[random];
    }

    public static String getHeadImg()
    {
        int random = new Random().nextInt(headImgs.length);
        return headImgs[random];
    }



    // 计算出该TextView中文字的长度(像素)
    public static float getTextViewLength(TextView textView, String text) {
        TextPaint paint = textView.getPaint();
        // 得到使用该paint写上text的时候,像素为多少
        float textLength = paint.measureText(text);
        return textLength;
    }

    public static int random(int start, int end) {
        //创建Random类对象
        Random random = new Random();
        //产生随机数
        int number = random.nextInt(end - start + 1) + start;
        return number;
    }

    /**
     * 判断是否安装了QQ
     *
     * @param context
     * @return
     */
    public static boolean isQQClientInstalled(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName.toLowerCase(Locale.ENGLISH);
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }


    //处理账号， 带*号
    public static String getAccount(String account) {
        String str = "";
        if (!TextUtils.isEmpty(account)) {
            if (account.length() == 11)   //手机号
            {
                str = account.substring(0, 3) + "****" + account.substring(7, 11);
            } else if (account.contains("@")) {
                int index = account.indexOf("@");
                if (index > 3) {
                    str = account.substring(0, 3) + "****" + account.substring(index);
                } else {
                    str = "****" + account.substring(index);
                }
            } else if (account.length() >= 15) {
                str = account.substring(0, 4) + " **** **** " + account.substring(account.length() - 3);
            } else if (account.length() >= 4) {
                str = account.substring(0, 3) + "****" + account.substring(account.length() - 3);
            } else {
                str = account;
            }
        }
        return str;
    }


    //数字显示处理，去掉末尾的0
    public static String numClearZero(String num) {
        if (TextUtils.isEmpty(num)) {
            num = "";
        } else {
            if (num.contains(".")) {
                while (num.endsWith("0")) {
                    num = num.substring(0, num.length() - 1);
                }
                while (num.endsWith(".")) {
                    num = num.substring(0, num.length() - 1);
                }
            }
        }
        return num;
    }


    //数字显示处理，保留几位小数点   length: 几位小数点
    public static String numDecimalFormat(String num, int length) {
        try {
            String decimalStr = "0";
            if (length > 0) {
                decimalStr += ".";
                for (int i = 0; i < length; i++) {
                    decimalStr += "0";
                }
            }
            DecimalFormat format = new DecimalFormat(decimalStr);
            String a = format.format(new BigDecimal(num));
            return a;
        } catch (Exception e) {
            return num;
        }
    }

    public static void closeApp() {
//        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    public static String getUUID(Context context) {
        String uuid = SPUtil.getStringValue(context, "PREFS_DEVICE_ID", "");
        if (TextUtils.isEmpty(uuid)) {
            final String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            try {
                if (!"9774d56d682e549c".equals(androidId)) {
                    uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8")).toString();
                } else {
                    @SuppressLint("MissingPermission") final String deviceId = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
                    uuid = deviceId != null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")).toString() : UUID.randomUUID().toString();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            SPUtil.putValue(context, "PREFS_DEVICE_ID", uuid);
        }
        return uuid.replace("-", "_");
    }


    /**
     * 获取app当前的渠道号或application中指定的meta-data
     *
     * @return 如果没有获取成功(没有对应值 ， 或者异常)，则返回值为空
     */
    public static String getAppMetaData(Context context, String key) {
        if (context == null || TextUtils.isEmpty(key)) {
            return null;
        }
        String channelNumber = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        channelNumber = applicationInfo.metaData.get(key) + "";
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channelNumber;
    }


    public static boolean isWifi(Context context) {
        if (getNetworkClass(context) == ConnectivityManager.TYPE_WIFI) {
            return true;
        } else {
            return false;
        }
    }

    private static int getNetworkClass(Context context) {
        int networkType = ConnectivityManager.TYPE_MOBILE;
        try {
            final NetworkInfo network = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            if (network != null && network.isAvailable() && network.isConnected()) {
                int type = network.getType();
                if (type == ConnectivityManager.TYPE_WIFI) {
                    networkType = ConnectivityManager.TYPE_WIFI;
                } else if (type == ConnectivityManager.TYPE_MOBILE) {
                    TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                    networkType = telephonyManager.getNetworkType();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return networkType;
    }


    //万 级转换
    public static String numberFormat(int num) {
        String numStr = num + "";
        if (num >= 10000) {
            DecimalFormat format = new DecimalFormat("0.0");
            numStr = format.format(num / 10000) + "万";
        }
        return numStr;
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {

        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        System.out.println("Drawable转Bitmap");
        Bitmap.Config config =
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                        : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        //注意，下面三行代码要用到，否则在View或者SurfaceView里的canvas.drawBitmap会看不到图
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }


    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static void copy(Context context, String msg, boolean... ishowTost) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("code", msg);
        clipboard.setPrimaryClip(clip);
        if (ishowTost.length > 0 && (boolean) ishowTost[0]) {
            CommToast.showToast(context, "已复制");
        }
    }

    /**
     * 获取手机大小（分辨率）
     */
    public static DisplayMetrics getScreenPix(Activity activity) {
        DisplayMetrics displaysMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displaysMetrics);
        return displaysMetrics;
    }

    /**
     * 判断SDCard是否可用
     */
    public static boolean existSDCard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }


    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param dipValue
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    // 获取手机状态栏高度
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    public static List<PackageInfo> getAppList(Context context) {
        PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);
        // 判断是否系统应用：
        List<PackageInfo> apps = new ArrayList<PackageInfo>();
        for (int i = 0; i < packageInfoList.size(); i++) {
            PackageInfo pak = (PackageInfo) packageInfoList.get(i);
            //判断是否为系统预装的应用
            if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
                // 第三方应用
                apps.add(pak);
            } else {
                //系统应用
            }
        }
        return apps;
    }

    //启动一个app
    public static void startAPP(Context context, String appPackageName) {
        try {
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(appPackageName);
            context.startActivity(intent);
        } catch (Exception e) {
            CommToast.showToast(context, "没有安装");
        }
    }


    /**
     * 设置键盘展现和关闭
     *
     * @param bShow
     * @param context
     * @param view
     */
    public static void showKeyBoard(boolean bShow, Context context, View view) {
        if (bShow) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        } else {
            InputMethodManager imm = (InputMethodManager) context
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }


    //手机号检查
    public static boolean isChinaPhoneLegal(String str) {
        String regExp = "^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }


    /**
     * 获取版本号名称
     *
     * @return 当前应用的版本号
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取版本号code
     *
     * @return
     */
    public static int getVersionCode(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            int version = info.versionCode;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    //通过反射获取类的属性和属性值
    public static Map<String, String> getFieldMap(Object object) {
        Map<String, String> map = new HashMap<>();
        Field fields[] = object.getClass().getDeclaredFields();//cHis 是实体类名称
        try {
            Field.setAccessible(fields, true);
            for (int i = 0; i < fields.length; i++) {
                String name = fields[i].getName();
                String value = "";
                if (fields[i].get(object) != null) {
                    value = fields[i].get(object).toString();
                }
                map.put(name, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    public static File uri2File(Context context, Uri uri) {
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = context.getContentResolver().query(uri, proj, null, null, null);
        if (actualimagecursor == null) {
            img_path = uri.getPath();
        } else {
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor
                    .getString(actual_image_column_index);
        }
        File file = new File(img_path);
        return file;
    }

    //压缩图片
    public static File compressImageToFile(File file) {
        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        if (bitmap == null) {
            return null;
        }
        // 0-100 100为不压缩
        int options = 50;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把压缩后的数据存放到baos中
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
        try {
            File temp_file = new File(Environment.getDataDirectory(), "temp_pic.jpg");
            FileOutputStream fos = new FileOutputStream(temp_file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
            return temp_file;
        } catch (Exception e) {
            e.printStackTrace();
            return file;
        }
    }

    /**
     * 将字符串的集合用逗号间隔拼接为字符串
     *
     * @param strList 字符串的集合
     * @return
     */
    public static String listToString(List<String> strList) {
        if (strList == null || strList.isEmpty()) {
            return null;
        }
        String str = "";
        for (String s : strList) {
            str = (TextUtils.isEmpty(str) ? s : str + "," + s);
        }
        return str;
    }

    //double科学计算法处理  maxLenth最高保留几位 minLength最少保留几位
    public static String formatDouble(double d, int maxLenth, int minLength) {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(minLength);
        //设置保留多少位小数
        nf.setMaximumFractionDigits(maxLenth);
        // 取消科学计数法
        nf.setGroupingUsed(false);
        //返回结果
        return nf.format(d);
    }


    //double科学计算法处理  maxLenth最高保留几位 minLength最少保留几位
    public static String formatDouble(double d, int maxLenth, int minLength, boolean isUp, boolean isDown) {
        String s = d + "";
        if (!TextUtils.isEmpty(s) && s.contains(".")) {
            int a = s.length() - s.indexOf(".") - 1;
            if (a > 2) { //小数位大于2向上取整
                if (isUp) {
                    d = new BigDecimal(d).setScale(3, BigDecimal.ROUND_DOWN).doubleValue();
                    BigDecimal b = new BigDecimal(d);
                    d = b.setScale(2, BigDecimal.ROUND_UP).doubleValue();
                }
            }
            if (a > 5) {
                if (isDown) {
                    BigDecimal b = new BigDecimal(d);
                    d = b.setScale(5, BigDecimal.ROUND_DOWN).doubleValue();
                }
            }
        }

        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(minLength);
        //设置保留多少位小数
        nf.setMaximumFractionDigits(maxLenth);
        // 取消科学计数法
        nf.setGroupingUsed(false);
        //返回结果
        return nf.format(d);
    }

    /**
     * 控制输入框输入数字保留小数点位数  在addTextChangedListener里面调用
     *
     * @param s     Editext  CharSequence
     * @param et    Editext 对象
     * @param digit 保留几位小数
     */
    public static void mangeEditextDigit(CharSequence s, EditText et, int digit) {
        String str = s.toString();
        int len = s.length();
        if (str.contains(".")) {
            //控制小数点后面位数
            if (len - 1 - str.indexOf(".") > digit) {
                s = str.subSequence(0,
                        str.indexOf(".") + digit + 1);
                et.setText(s.toString());
                et.setSelection(s.length());
            }
        }
        if (str.substring(0).equals(".")) {
            //输入点，自动补充成0.
            s = "0" + s;
            et.setText(s.toString());
            et.setSelection(s.length());
        }

        if (str.startsWith("0")
                && len > 1) {
            //以0开头不允许输入连续的0如00，000
            if (!str.substring(1, 2).equals(".")) {
                et.setText(s.subSequence(0, 1).toString());
                et.setSelection(s.subSequence(0, 1).toString().length());
            }
        }
        if (len - str.replace(".", "").length() > 1) {
            //不允许输入1个以上的小数点
            et.setText(s.subSequence(0, len - 1).toString());
            et.setSelection(s.subSequence(0, len - 1).toString().length());
        }
    }

    //至少包含两个点
    public static boolean containMorethanTwoPoint(String str) {
        Pattern pattern = Pattern.compile("^.*[.].*[.].*$");
        return pattern.matcher(str).matches();
    }

    //禁止重复点击
    public static void unallowQuickClick(final View view) {
        view.setEnabled(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                view.setEnabled(true);
            }
        }, 1000);
    }


    //禁止重复点击
    public static void unallowQuickClickWithTimes(final View view, long mills) {
        view.setEnabled(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                view.setEnabled(true);
            }
        }, mills);
    }


    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    public static void callPhone(Context context, String phoneNum) {
        try {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri data = Uri.parse("tel:" + phoneNum);
            intent.setData(data);
            context.startActivity(intent);
        } catch (Exception e) {
            CommToast.showToast(context, "您的设备不支持打电话");
        }
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return by Hankkin at:2015-10-07 21:15:59
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return by Hankkin at:2015-10-07 21:16:13
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 随机指定范围内N个不重复的数 在初始化的无重复待选数组中随机产生一个数放入结果中，
     * 将待选数组被随机到的数，用待选数组(len-1)下标对应的数替换 然后从len-2里随机产生下一个随机数，如此类推
     *
     * @param max 指定范围最大值
     * @param min 指定范围最小值
     * @param n   随机数个数
     * @return int[] 随机数结果集
     */
    public static List<Integer> randomArray(int min, int max, int n) {
        int len = max - min + 1;
        if (max < min || n > len) {
            return null;
        }
        // 初始化给定范围的待选数组
        int[] source = new int[len];
        for (int i = min; i < min + len; i++) {
            source[i - min] = i;
        }
        int[] result = new int[n];
        List<Integer> listNumber = new ArrayList<>();
        Random rd = new Random();
        int index = 0;
        for (int i = 0; i < result.length; i++) {
            // 待选数组0到(len-2)随机一个下标
            index = Math.abs(rd.nextInt() % len--);
            // 将随机到的数放入结果集
            result[i] = source[index];
            // 将待选数组中被随机到的数，用待选数组(len-1)下标对应的数替换
            source[index] = source[len];
            listNumber.add(result[i]);
        }
        return listNumber;
    }


}
